<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card >
      <!-- 头部搜索 -->
      <el-row>
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="params.query" clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" class="btn" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
<!-- 用户列表 -->
      <el-table
      :data="userList"
      style="width: 100%" border>
      <el-table-column prop="id" abel="#" type="index"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="电话">
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="角色">
      </el-table-column>
      <el-table-column
        prop="mg_state"
        label="状态">
        <!-- 运用到了作用域插槽 data为接收子向父亲传的值（表格向users界面） 为整个数据对象 通过双向数据绑定 可以实现开关 -->
        <template slot-scope="data">
          <el-switch
        v-model="data.row.mg_state"
        active-color="#409eff"
        inactive-color="#dcdfe6" @change="userStatusChange(data.row)">
        </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="mg_state"
        label="操作">
        <template slot-scope="data">
        <div class="bt">
          <el-button type="primary" size="mini"  icon="el-icon-edit"  @click="index(data.row.id)"></el-button>
        <el-button type="danger"   size="mini"  icon="el-icon-delete"  @click="del(data.row.id)"></el-button>
        <el-tooltip  effect="dark" content="设置" placement="top">
          <el-button type="warning"  size="mini" icon="el-icon-setting" @click="set(data.row)"></el-button>
        </el-tooltip>
        </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block">
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="params.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      <!-- size-change和current-change事件来处理显示页码大小和当前页码数变动时候触发的事件 -->
    </el-pagination>
    </div>
    </el-card>
    <!-- 用户对话框 -->
     <!-- :visible.sync 控制对话框显示隐藏 -->
    <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%">
        <!-- 内容主体区 是一个默认插槽-->
        <el-form :model="userRuleForm" :rules="userRules" ref="ruleFormRef" label-width="70px" >
          <!-- ref在普通标签获取dom对象 -->
          <!-- 在组件上 则获取组件的实例 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userRuleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userRuleForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userRuleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="userRuleForm.mobile"></el-input>
          </el-form-item>
          </el-form>
        <!-- 底部区域 为具名插插-->
      <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addUsers">确 定</el-button>
    </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
        title="编辑用户"
        :visible.sync="setDialogVisible"
        width="50%">
        <!-- 内容主体区 是一个默认插槽-->
        <el-form :model="setUserForm" :rules="userRules" ref="ruleFormRef" label-width="70px" >
          <!-- ref在普通标签获取dom对象 -->
          <!-- 在组件上 则获取组件的实例 -->
          <el-form-item label="用户名" >
            <el-input v-model="setUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="setUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="setUserForm.mobile"></el-input>
          </el-form-item>
          </el-form>
        <!-- 底部区域 为具名插插-->
      <span slot="footer" class="dialog-footer">
      <el-button @click="setDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="setUsers">确 定</el-button>
    </span>
    </el-dialog>

     <!-- 修改用户角色 对话框 -->
     <el-dialog
        title="提示"
        :visible.sync="UserDialogVisible"
        width="50%" @close="UserDialogClose" ref="UserDialogRef">
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前用户角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="userRoles" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :value="item.id"
              :label="item.roleDesc"
              :v-model="userRoles">
            </el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="UserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="selectSure">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    const checkEmail = (rule, value, callback) => { // 自定义校验规则
      const regEmaill = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (!regEmaill.test(value)) return callback(new Error('邮箱格式错误'))
      callback()
    }
    const checkmobile = (rule, value, callback) => {
      const regmobile = /^1(3|4|5|6|7|8|9)\d{9}$/
      if (!regmobile.test(value)) return callback(new Error('手机号格式错误'))
      callback()
    }
    return {
      userList: [],
      params: {
        query: '',
        pagenum: 1, // 当前处于的页码
        pagesize: 2 // 当前一页显示几条
      },
      total: 0,
      addDialogVisible: false,
      setDialogVisible: false,
      UserDialogVisible: false,
      userRuleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      setUserForm: {
        username: '',
        email: '',
        mobile: ''
      },
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      userInfo: {}, // 点击设置按钮获取当前用户信息
      rolesList: {}, // 所有角色信息
      userRoles: '' // 要赋予当前用户的角色
    }
  },
  methods: {
    async getUserList () { // 获取用户信息
      const { data: res } = await this.$http.get('users', { params: this.params })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res.data)
      this.userList = res.data.users // 将用户信息赋值给userList，以便循环渲染
      this.total = res.data.total // 用户总数，作已展示
      // console.log(this.userList)
    },
    handleSizeChange (newSize) { // 每页显示的数量变化触发函数
      this.params.pagesize = newSize // newSize参数为最新的分页数，在调用接口获取数据重新展示
      this.getUserList()
    },
    handleCurrentChange (newNum) {
      this.params.pagenum = newNum // newSize参数为最新的页码数
      this.getUserList()
    },
    async userStatusChange (data) { // 表格中用户状态改变函数
      const { data: res } = await this.$http.put('users/' + data.id + '/state/' + data.mg_state) // 调用接口发送最新用户状态过去，改变用户状态
      if (res.meta.status !== 200) {
        data.mg_state = !data.mg_state
        return this.open1('修改状态异常', 'warning')
      }
      this.open1('修改状态成功', 'success')
    },
    open1 (str, type) { // 自动关闭的提示框
      const h = this.$createElement
      this.$notify({ title: str, message: h('i', { style: 'color: teal' }), type: type })
    },
    addUser () { // 点击弹出对话框
      this.addDialogVisible = true
    },
    addUsers () { // 新增用户对话框的确定按钮
      this.$refs.ruleFormRef.validate(boolean => {
        if (!boolean) return this.$message.error('请检查填写是否正确')
        this.addUserForm()
      })
    },
    async addUserForm () { // 新增用户请求
      const { data: res } = await this.$http.post('users', this.userRuleForm)
      if (res.meta.status !== 201) return this.open1('创建用户失败', 'warning')
      this.open1('创建用户成功', 'success')
      this.addDialogVisible = false // 关闭对话框
      this.getUserList()
    },
    async index (id) { // 修改用户点击按钮 弹出对话框 发请求赋值
      this.setDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.open1('获取用户信息', 'warning')
      this.setUserForm = res.data
    },
    setUsers () { // 修改对话框中的确定按钮
      this.$refs.ruleFormRef.validate(boolean => {
        if (!boolean) return this.$message.error('请检查填写是否正确')
        this.setUserForms()
      })
    },
    async setUserForms () { // 修改用户请求
      const datas = { email: this.setUserForm.email, mobile: this.setUserForm.mobile }
      const { data: res } = await this.$http.put('users/' + this.setUserForm.id, datas)
      if (res.meta.status !== 200) return this.open1('修改用户失败', 'warning')
      this.open1('修改用户成功', 'success')
      this.setDialogVisible = false // 关闭对话框
      this.getUserList()
    },
    del (id) { // 删除用户按钮
      this.delOpen(id)
    },
    async delOpen (id) { // 删除按钮
      const resultDel = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).catch(res => res)
      if (resultDel === 'confirm') {
        this.delUrl(id)
      }
    },
    async delUrl (id) {
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.open1('删除用户失败', 'warning')
      this.open1('删除用户成功', 'success')
      this.getUserList()
    },
    async set (data) { // 设置按钮点击弹框
      this.UserDialogVisible = true
      this.userInfo = data
      const { data: res } = await this.$http.get('roles') // 获取全部角色信息
      if (res.meta.status !== 200) return this.open1('删除用户失败', 'warning')
      this.rolesList = res.data
    },
    async selectSure () {
      const { data: res } = await this.$http.put('users/' + this.userInfo.id + '/role', { rid: this.userRoles }) // 获取全部角色信息
      if (res.meta.status !== 200) return this.open1(res.meta.msg, 'warning')
      this.getUserList()
      this.UserDialogVisible = false
    },
    UserDialogClose () {
      this.userRoles = ''
      this.userInfo = ''
    }
  },
  created () { // 钩子函数 发请求
    this.getUserList()
  },
  watch: { // 监听修改对话框是否关闭 关闭重置表单
    addDialogVisible (val) {
      if (!val) this.$refs.ruleFormRef.resetFields()
    },
    setDialogVisible (val) {
      if (!val) this.$refs.ruleFormRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 20px;
  font-size: 12px;
}
.btn {
  margin-left: 20px;
}
.el-table {
  margin:20px 0;
}
.bt {
display: flex;
}

</style>
